<?php
/**
 * Created by PhpStorm.
 * User: xiemi
 * Date: 2020/3/31
 * Time: 20:24
 */

namespace darksun;


class Log
{
    private $logPath;
    private $logName;
    private $logExt;

    public function __construct($logPath = null, $logName = 'default', $logExt = 'log')
    {
        if(empty($logPath)) $this->logPath = LOG;
        $this->logName = $logName;
        $this->logExt = $logExt;
    }

    private function getLogFile()
    {
        $logFile = $this->logPath.$this->logName.'_'.date('Ymd').'.'.$this->logExt;
        if(!is_file($logFile)){
            $dir = dirname($logFile);
            (is_dir($dir) || @mkdir($dir, 0755));
        }
        $file = fopen($logFile,'a+');
        return $file;
    }

    public function warn($msg)
    {
        $file = $this->getLogFile();
        $line = '['.date('Y-m-d H:i:s').'][warn] '.$msg."\n";
        fwrite($file, $line);
        fclose($file);
    }

    public function debug($msg)
    {
        $file = $this->getLogFile();
        $line = '['.date('Y-m-d H:i:s').'][debug] '.$msg."\n";
        fwrite($file, $line);
        fclose($file);
    }

    public function info($msg)
    {
        $file = $this->getLogFile();
        $line = '['.date('Y-m-d H:i:s').'][info] '.$msg."\n";
        fwrite($file, $line);
        fclose($file);
    }

    public function error($msg)
    {
        $file = $this->getLogFile();
        $debugInfo = debug_backtrace();      
        foreach($debugInfo as $key => $val){
            $stack = "[";
            if(array_key_exists("file", $val)){
                $stack .= "file:" . $val["file"].",";
            }
            if(array_key_exists("line", $val)){
                $stack .= "line:" . $val["line"].",";
            }
            if(array_key_exists("function", $val)){
                $stack .= "function:" . $val["function"];
            }
            $stack .= "]";
            $line = '['.date('Y-m-d H:i:s').'][error] '.$stack.$msg."\n";
            fwrite($file, $line);
        }
        fclose($file);
    }
}